package Back;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import Dao.dt;
import org.example.User;

public class ReplaySelectorFrame extends JFrame {

    private dt dao;
    private JComboBox<String> replayComboBox;
    private User currentUser;
    public ReplaySelectorFrame(User currentUser) {
        super("回放选择器");
        this.currentUser=currentUser;
        initializeUI();
        connectToDatabase();
        loadReplayNames();

        // 启动定时刷新任务（每5秒刷新一次）
        startAutoRefreshTask();
    }

    private void initializeUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 600);
        setLayout(null); // 使用绝对布局（可考虑改用布局管理器）
    }

    private void connectToDatabase() {
        dao = new dt();
        dao.connect();
    }

    private void loadReplayNames() {
        List<String> replayNames = dao.getReplayNames(currentUser);

        if (replayComboBox == null) {
            // 首次加载，创建下拉框
            replayComboBox = new JComboBox<>(replayNames.toArray(new String[0]));
            replayComboBox.setBounds(0, 25, 150, 30);
            add(replayComboBox);
        } else {
            // 更新已有下拉框
            replayComboBox.removeAllItems();
            for (String name : replayNames) {
                replayComboBox.addItem(name);
            }
        }

        // 按钮只添加一次
        if (getComponentCount() < 2) {
            JButton playButton = new JButton("播放选中回放");
            playButton.setBounds(170, 25, 120, 30);
            playButton.addActionListener(e -> {
                String selectedName = (String) replayComboBox.getSelectedItem();
                if (selectedName != null) {
                    MAP mapData = dao.getnewmap(selectedName);
                    mapData.allpath = dao.createCarPathArray(selectedName, mapData.carcount, mapData.max_time);
                    if (mapData != null) {
                        ReplayPanel replayPanel = new ReplayPanel(mapData);
                        JFrame replayFrame = new JFrame("回放：" + selectedName);
                        replayFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                        replayFrame.setSize(800, 800);
                        replayFrame.add(replayPanel, BorderLayout.CENTER);
                        replayFrame.setVisible(true);
                    }
                }
            });
            add(playButton);
        }

        revalidate();
        repaint();
    }

    /**
     * 启动定时刷新任务
     */
    private void startAutoRefreshTask() {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            SwingUtilities.invokeLater(() -> {
                System.out.println("🔄 正在刷新回放列表...");
                dt tempDao = new dt();
                tempDao.connect();
                List<String> updatedNames = tempDao.getReplayNames(currentUser);
                tempDao.closeConnection();

                // 保留当前选中项
                String currentSelectedItem = (String) replayComboBox.getSelectedItem();

                // 清空并重新添加选项
                replayComboBox.removeAllItems();
                for (String name : updatedNames) {
                    replayComboBox.addItem(name);
                }

                // 如果之前有选中项，则尝试恢复
                if (currentSelectedItem != null) {
                    replayComboBox.setSelectedItem(currentSelectedItem);
                }
            });
        }, 0, 5, TimeUnit.SECONDS); // 初始延迟0s，之后每5秒执行一次
    }

    // 窗口关闭时关闭数据库连接
    public void setupCloseOperation() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                if (dao != null) {
                    dao.closeConnection();
                }
            }
        });
    }

    // 主方法可以直接运行该窗口
//    public static void main(String[] args) {
//        SwingUtilities.invokeLater(() -> {
//            ReplaySelectorFrame frame = new ReplaySelectorFrame(c);
//            frame.setVisible(true);
//        });
//    }
}
